// Package middleware pkg/middleware/recovery.go
package middleware

import (
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"gozrd-admin-api/pkg/logger"
	"gozrd-admin-api/pkg/response"
	"gozrd-admin-api/pkg/traceid"
	"net/http"
	"runtime/debug"
)

// Recovery 恢复中间件，用于捕获所有panic并恢复
func Recovery() gin.HandlerFunc {
	return func(c *gin.Context) {
		defer func() {
			if err := recover(); err != nil {
				// 获取trace_id
				traceIDValue, exists := c.Get(traceid.TraceIDKey)
				traceID := ""
				if exists {
					traceID, _ = traceIDValue.(string)
				}

				// 记录错误日志
				logger.Error("发生严重错误，系统已恢复",
					zap.Any("error", err),
					zap.String("trace_id", traceID),
					zap.String("stack", string(debug.Stack())),
				)

				// 返回500错误
				response.Fail(c, http.StatusInternalServerError, "系统内部错误")
				c.Abort()
			}
		}()
		c.Next()
	}
}
